#!/bin/sh 
DEV=lo
DST=127.0.0.1
DPORT='5201 0xff'
if [ "$2" = '1' ] ; then
RATE=5mbit
LOSS=5%
DELAY=100ms
elif [ "$2" = '2' ] ; then
RATE=2mbit
LOSS=10%
DELAY=200ms
elif [ "$2" = '3' ] ; then
RATE=1mbit
LOSS=20%
DELAY=300ms
fi

status () {
    tc  qdisc show dev $DEV
    tc  class show dev $DEV
    tc  filter show dev $DEV
    exit 0
}
    
if [ "$1" = 'clean' ] ; then
    tc qdisc del dev $DEV root 2> /dev/null > /dev/null
    echo "-----------------------------------------------------------"
    echo "tc setting is cleaned"
    echo "-----------------------------------------------------------"
    exit 0
elif [ "$1" = 'status' ] ; then
    status
elif [ "$1" = 'delay' ] ; then
    tc qdisc add dev $DEV root netem delay $DELAY
elif [ "$1" = 'loss' ] ; then
    tc qdisc add dev $DEV root netem loss $LOSS
elif [ "$1" = 'rate' ] ; then
    tc qdisc add dev $DEV root handle 1: htb default 2
    tc class add dev $DEV parent 1:1 classid 1:2 htb rate $RATE ceil $RATE prio 2
    tc qdisc add dev $DEV parent 1:2 handle 2: sfq perturb 10
    tc filter add dev $DEV protocol ip parent 1:0 u32 match ip dport $DPORT flowid 1:2
    #tc class add dev $DEV parent 1:1 classid 1:3 htb rate 1mbit ceil 1mbit prio 2
    #tc qdisc add dev $DEV parent 1:3 handle 3: sfq perturb 10
    #tc filter add dev $DEV protocol ip parent 1:0 u32 match ip dst 192.168.0.1 flowid 1:3
elif [ "$1" = 'duplicate' ] ; then
    tc qdisc add dev $DEV root netem duplicate 1%
elif [ "$1" = 'corrupt' ] ; then
    tc qdisc add dev $DEV root netem corrupt 0.2%
elif [ "$1" = 'disorder' ] ; then
    tc qdisc change dev $DEV root netem delay 10ms reorder 25% 50%
fi

echo "-----------------------------------------------------------"
echo "tc settings:"
echo "-----------------------------------------------------------"
    status
echo "-----------------------------------------------------------"
exit 0
